import axios from 'axios';

const http = axios.create({
    baseURL: "http://localhost:3111",

})

// 请求拦截器
http.interceptors.request.use(function (request) {
    const accessToken = localStorage.getItem('accessToken');
    if (accessToken) {
        request.headers.Authorization = `Bearer ${accessToken}`;
    }
    return request;
}, function (error) {
    return Promise.reject(error);
});

// 响应拦截器
http.interceptors.response.use(function (response) {
    return response;
}, async function (error) {
    const originalRequest = error.config;
    if (error.response.status === 401 && !originalRequest._retry) {
        originalRequest._retry = true;
        const refreshToken = localStorage.getItem('refreshToken');
        if (refreshToken) {
            try {
                const response = await axios.post('http://127.0.0.1:8000/refresh-token', { refreshToken });
                const newAccessToken = response.data.data.accessToken;
                localStorage.setItem('accessToken', newAccessToken);
                originalRequest.headers.Authorization = `Bearer ${newAccessToken}`;
                return axios(originalRequest);
            } catch (refreshError) {
                // 刷新 token 失败，跳转到登录页面
                localStorage.removeItem('accessToken');
                localStorage.removeItem('refreshToken');
                window.location.href = '/login';
            }
        }
    }
    return Promise.reject(error);
});

export default http;